var request = require('request');
// var request = request.defaults({
//     jar: true
// });

var cheerio = require('cheerio');
var getFullUrl = require('./utils').getFullUrl;
var cmdCall = require('./utils').cmdCall;
var fs = require('fs');
var path = require('path');

var __url = 'http://www.dianping.com/guangzhou';


function mockBrowserRequest(url, cb) {
    request({
        url: url,
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36',
            "Referer": "http://www.dianping.com/"
                //"Host": "www.dianping.com",
                //"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                //"Accept-Encoding": "gzip, deflate, sdch",
                //"Accept-Language": "zh-CN,zh;q=0.8",
                //"Cache-Control": "no-cache",
                //"Connection": "keep-alive",
                //"Cookie": 'avCtgScroll=0; showNav=#nav-tab|0|0; _hc.v="\"4b73a732-b036-4ac5-9292-945028c63908.1435982877\""; __utma=1.1296667065.1435984011.1435984011.1435984011.1; __utmc=1; __utmz=1.1435984011.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHOENIX_ID=0a017429-14e599edef5-178c6eb; s_ViewType=10; JSESSIONID=DE6183A83C9F56A249E7F6A7618AB045; aburl=1; cy=4; cye=guangzhou'
        }
    }, cb);
}

/**
 * 从 http://www.dianping.com/guangzhou/beauty
 * 得到 /search/category/4/10/g111 列表
 * @returns {Promise}
 */
function getSubCateList() {
    // 城市=广州 种类=丽人
    var selector = 'a.name[href="/guangzhou/beauty"]';

    return new Promise(function(fullful, reject) {
        var subCateList = [];
        request(__url, function(err, res, body) {
            console.log(res.cookie);
            var $ = cheerio.load(body);
            $(selector)
                .nextAll('.secondary-category') // not work ...
                .children('a[data-key][href]')
                .each(function(index, element) {
                    var rUrl = $(this).attr('href');
                    var fullUrl = getFullUrl(__url, rUrl);
                    //console.log(fullUrl);
                    subCateList.push(fullUrl);
                });
            fullful(subCateList);
        });
    });
}

/**
 * url 组合规则 xxxp1, xxxp2表示page = 1,2
 * @param url
 * @param pageIndex
 * @returns {string}
 */
function getPagedUrl(url, pageIndex) {
    if (pageIndex) {
        var pagedUrl = url + 'p' + pageIndex;
    }
    return pagedUrl || url;
}

/**
 * 从 http://www.dianping.com/search/category/4/50/g157
 * 得到商户列表
 * 从图片获取url /shop/5863924
 * <div class="pic" >
 <a target="_blank" href="/shop/5863924" xxx >
 <imgxxx/>
 </a>
 </div>
 * @param url
 * @param pageIndex
 * @returns {Promise}
 */
//function getShopList(url, pageIndex) {
function getShopList() {
    // var pageIndex = 1;
    var url = "http://www.dianping.com/search/category/4/50/g157";
    // var selector = 'div#shop-all-list ul';
    // var pagedUrl = getPagedUrl(url, pageIndex);
    // console.log(url);
    // var fileName = 'g157.html';

    var j = request.jar();
    url = __url;
    rootUrl = 'http://www.dianping.com/';
    request({
        url: url,
        jar: j
    }, function(err, res, body) {
        var cookie_string = j.getCookieString(rootUrl); // "key1=value1; key2=value2; ..."
        var cookies = j.getCookies(rootUrl);
        // console.log(body);
        console.log(cookies);
    });


    // 这里总是拿不到正确的页面，crul就可以,wget 也不行
    //mockBrowserRequest(url, function (err, res, body) {
    //    fs.writeFile(fileName, body, function (err) {
    //        if (err) {
    //            return console.log('write file err' + err);
    //        }
    //        console.log('-------------success-----------');
    //        console.log(fileName);
    //    });
    //    //
    //    console.log(body.length);
    //    //
    //    ////<a target="_blank" href="/shop/2545147"
    //    ////var regEx = /<a\s+target="_blank"\s+href="\/shop\/\d+?"/g;
    //    //var regEx = /href="\/shop\/\d+"/g;
    //    //console.log(regEx);
    //    //var list = body.match(regEx);
    //    //console.log(list);
    //});



    // call back not exec , other process ?
    //cmdCall('curl ' + url + ' > ' + fileName).then(function (body) {
    //    fs.readFile(fileName, 'utf8', function (err,doc) {
    //        if (err) {
    //            return console.log('write file err' + err);
    //        }
    //        console.log('-------------success-----------');
    //        //console.log(doc);
    //        console.log(body.length);
    //    });
    //});


    // var exec = require('child_process').exec;
    // var cmd = 'curl ' + url + ' > ' + fileName;
    // exec(cmd, function(error, stdout, stderr) {
    //     fs.readFile(fileName, 'utf8', function (err, doc) {
    //         if (err) {
    //             return console.log('write file err' + err);
    //         }
    //         console.log('-------------success-----------');
    //         //console.log(doc);
    //         console.log(doc.length);
    //     });
    // });
}
//getSubCateList().then(function (res) {
//    console.log(res);
//    getShopList();
//});
// getShopList();

request({
    url: 'http://www.dianping.com/search/category/4/50/g157',
    method: 'get',
    headers: {
        'User-Agent': 'request'
    },
    timeout: 5000
}, function(err, res, body) {
    console.log(body);
})